package com.runen.infinitemovement.activity;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.AllRoadAdapter;
import com.runen.infinitemovement.adapter.RoadTextAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MyLongRoadEntity;
import com.runen.infinitemovement.model.entity.PathPathSectionListEntity;
import com.runen.infinitemovement.model.entity.PathSectionListEntity;
import com.runen.infinitemovement.model.entity.PolyLineEntity;
import com.runen.infinitemovement.model.entity.RideRoteJsonEntity;
import com.runen.infinitemovement.model.entity.RoadLineEntity;
import com.runen.infinitemovement.model.entity.SaveLongDataEntity;
import com.runen.infinitemovement.model.enums.ChallengeType;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.MapUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.CommonDetailsPoppupWindow;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CheckRoadActivity extends BaseActivity {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.mapView)
    TextureMapView mapView;
    @BindView(R.id.rv_challenge_list)
    RecyclerView rvChallengeList;
    @BindView(R.id.rv_map)
    RelativeLayout rvMap;
    @BindView(R.id.ll_road_introduce)
    LinearLayout llRoadIntroduce;
    @BindView(R.id.rl_mid)
    RelativeLayout rlMid;
    @BindView(R.id.rv_all_road)
    RecyclerView rvAllRoad;
    @BindView(R.id.ll_tips)
    LinearLayout llTips;
    @BindView(R.id.tv_no_tips)
    TextView tvNoTips;
    @BindView(R.id.tv_start_end_name)
    TextView tvStartEndName;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.main_line)
    View mainLine;
    @BindView(R.id.rl_line)
    View rlLine;
    private RoadTextAdapter textAdapter;
    private AllRoadAdapter allRoadAdapter;
    private MyLongRoadEntity.DataBean data;
    private AMap aMap;
    private List<RoadLineEntity.DataBean> roadLinedataList = new ArrayList<>();
    private String introduction;
    private String name;
    private String sectionId;
    private List<PathSectionListEntity> pathSectionListEntityList;
    private List<PolyLineEntity> polyLineEntityList = new ArrayList<>();
    private PolyLineEntity polyLineEntity;
    private double completionRate;
    private String headImgUrl;

    //挑战路线的下标
    private int challengePathIndex = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_road_v2;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                llTop.setPadding(0, CommonUtil.getStatusBarHeight(CheckRoadActivity.this)
                        , 0, 0);
            }
        });
        initMap(savedInstanceState);

        data = JsonUtils.fromJson(getIntent().getStringExtra("roadData"), MyLongRoadEntity.DataBean.class);

        initTips();

        if (null != data && null != data.pathPathSectionList && data.pathPathSectionList.size() > 0) {
            //如果当前挑战路线不对null,先取出当前正在挑战的路线
            if (data.nowSectionInfoDTO != null) {
                setChallengeStatus();
                selectChallenge();
            }
        }

        initAllRoad();
        initTextAdapter();
        loadData();
        if (data != null) {
            setView(data);
        }
    }

    private void initMap(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        MapUtils.setCustomMap(this, aMap);
//        aMap.setMapType(MAP_TYPE_SATELLITE);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setLogoBottomMargin(-200);
        aMap.getUiSettings().setRotateGesturesEnabled(false);
    }

    private void initTips() {
        if (data != null && data.nowSectionInfoDTO != null) {
            tvNoTips.setVisibility(View.GONE);
            llTips.setVisibility(View.VISIBLE);
            String startEndName = "%s - %s";
            tvStartEndName.setText(String.format(startEndName, data.nowSectionInfoDTO.startPoint, data.nowSectionInfoDTO.endPoint));
            String progress = "进度 %s";
            tvProgress.setText(String.format(progress, CommonUtil.Double2position(data.nowSectionInfoDTO.completionRate * 100) + "%"));
        } else {
            tvNoTips.setVisibility(View.VISIBLE);
            llTips.setVisibility(View.GONE);
        }
    }

    private void initLoadRoadLine(PathPathSectionListEntity pathSectionListEntity) {
        if (pathSectionListEntity != null) {
            introduction = pathSectionListEntity.introduction;
            name = pathSectionListEntity.pathName;
            if (pathSectionListEntity.pathSectionList != null && pathSectionListEntity.pathSectionList.size() > 0) {
                allRoadAdapter.setNewData(pathSectionListEntity.pathSectionList);
                allRoadAdapter.checkPosition(0);
                sectionId = allRoadAdapter.getData().get(0).sectionId;
                if (saveLongDataEntities != null && saveLongDataEntities.size() > 0) {
                    for (int i = 0; i < saveLongDataEntities.size(); i++) {
                        if (allRoadAdapter.getData().get(0).sectionId.equals(saveLongDataEntities.get(i).sectionId)) {
                            if (saveLongDataEntities.get(i).roteJsonEntities != null && saveLongDataEntities.get(i).roteJsonEntities.size() > 0) {
                                List<LatLng> latLngs = new ArrayList<>();
                                for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                    RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                    latLngs.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                }
                                if (saveLongDataEntities.get(i).polyline != null) {
                                    saveLongDataEntities.get(i).polyline.setDottedLine(false);
                                } else {
                                    saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#4d", "#");
                                    saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                            addAll(latLngs)
                                            .width(20)
                                            .setDottedLine(false) //打开虚线
                                            .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                }
                            }
                        } else {
                            if (saveLongDataEntities.get(i).roteJsonEntities != null && saveLongDataEntities.get(i).roteJsonEntities.size() > 0) {
                                List<LatLng> latLngs = new ArrayList<>();
                                for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                    RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                    latLngs.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                }
                                if (saveLongDataEntities.get(i).polyline != null) {
                                    saveLongDataEntities.get(i).polyline.setDottedLine(true);
                                } else {
                                    saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#", "#4d");
                                    saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                            addAll(latLngs)
                                            .width(20)
                                            .setDottedLine(true) //打开虚线
                                            .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 地图选择路线时刷新路线Adapter
     *
     * @param pathSectionListEntity
     * @param sectionId
     */
    private void initLoadRoadLine2(PathPathSectionListEntity pathSectionListEntity, String sectionId) {
        if (pathSectionListEntity != null) {
            introduction = pathSectionListEntity.introduction;
            name = pathSectionListEntity.pathName;
            if (pathSectionListEntity.pathSectionList != null && pathSectionListEntity.pathSectionList.size() > 0) {
                allRoadAdapter.setNewData(pathSectionListEntity.pathSectionList);
                for (int i = 0; i < allRoadAdapter.getData().size(); i++) {
                    if (sectionId.equals(allRoadAdapter.getData().get(i).sectionId)) {
                        allRoadAdapter.checkPosition(i);
                    }
                }
            }
        }
    }

    private void setView(MyLongRoadEntity.DataBean data) {
        showDialog("加载地图中...", false);
        if (null != data) {
            headImgUrl = data.headImgUrl;
            if (data.nowSectionInfoDTO != null) {
                completionRate = data.nowSectionInfoDTO.completionRate;
            }
            if (data.pathPathSectionList != null && data.pathPathSectionList.size() > 0) {
                pathSectionListEntityList = new ArrayList<>();
                for (int i = 0; i < data.pathPathSectionList.size(); i++) {
                    PathPathSectionListEntity pathPathSectionList = data.pathPathSectionList.get(i);
                    if (pathPathSectionList.pathSectionList != null && pathPathSectionList.pathSectionList.size() > 0) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int j = 0; j < pathPathSectionList.pathSectionList.size(); j++) {
                                    try {
                                        PathSectionListEntity pathSectionListEntity = pathPathSectionList.pathSectionList.get(j);
                                        pathSectionListEntityList.add(pathSectionListEntity);
                                        setRideRoteQuery(pathSectionListEntity.translationFile, pathSectionListEntity.color,
                                                pathSectionListEntity.iconLink, pathSectionListEntity.iconLinkOver, pathSectionListEntity.icon,
                                                pathSectionListEntity.sectionId, pathPathSectionList.mileage, pathSectionListEntity.difficulty);
                                        Thread.sleep(200);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();

                    }
                }
            }
        }
    }

    private List<SaveLongDataEntity> saveLongDataEntities = new ArrayList<>();
    private SaveLongDataEntity saveLongDataEntity;

    public void setRideRoteQuery(String translationFile, String color, String iconLink, String iconLinkOver,
                                 String icon, String sectionId, double mileage, int difficulty) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new ChallengeAPI().getRideRoteQuery(translationFile, new BaseResultCallback<List<com.runen.infinitemovement.model.entity.RideRoteJsonEntity>>() {
                    @Override
                    public void onResponse(List<RideRoteJsonEntity> response) {
                        saveLongDataEntity = new SaveLongDataEntity();
                        saveLongDataEntity.color = color;
                        saveLongDataEntity.iconLink = iconLink;
                        saveLongDataEntity.iconLinkOver = iconLinkOver;
                        saveLongDataEntity.roteJsonEntities = response;
                        saveLongDataEntity.sectionId = sectionId;
                        saveLongDataEntity.icon = icon;
                        saveLongDataEntity.mileage = mileage;
                        saveLongDataEntity.difficulty = difficulty;
                        saveLongDataEntities.add(saveLongDataEntity);
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("RideRote", JsonUtils.toJson(saveLongDataEntity));
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                });
            }
        }).start();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String str = bundle.getString("RideRote");
                    SaveLongDataEntity saveLongDataEntity = JsonUtils.fromJson(str, SaveLongDataEntity.class);
                    if (saveLongDataEntity != null) {
                        pathPoint(saveLongDataEntity);
                    }
                    break;
            }

            return false;
        }
    });


    /**
     * 路线展示
     *
     * @param rideRoteJsonEntity
     * @param color
     * @param iconLink
     * @param iconLinkOver
     */
    private List<LatLng> latLngList = new ArrayList<>();
    private LatLngBounds.Builder newBounds = new LatLngBounds.Builder();
    private List<RideRoteJsonEntity> rideRoteJsonEntity;

    private void pathPoint(SaveLongDataEntity saveLongDataEntity) {
        polyLineEntity = new PolyLineEntity();
        polyLineEntity.sectionId = saveLongDataEntity.sectionId;
        polyLineEntity.color = saveLongDataEntity.color;
        polyLineEntity.latLngs = new ArrayList<>();
        List<LatLng> latLngs = new ArrayList<>();
        rideRoteJsonEntity = saveLongDataEntity.roteJsonEntities;

        List<LatLng> fullLatLngs = new ArrayList<>();
        List<LatLng> xuLatLngs = new ArrayList<>();
        if (data.nowSectionInfoDTO != null) {
            if (data.nowSectionInfoDTO.sectionId.equals(saveLongDataEntity.sectionId)) {
                double lastDistance = saveLongDataEntity.mileage * completionRate;
                for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
                    if (lastDistance < rideRoteJsonEntity.get(i).mileage) {
                        xuLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                    } else {
                        fullLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                    }
                }

                if (xuLatLngs.size() > 0) {
                    setMarker(xuLatLngs.get(0).latitude, xuLatLngs.get(0).longitude, saveLongDataEntity.iconLink);
                }
                if (fullLatLngs.size() > 0) {
                    setMarker(fullLatLngs.get(0).latitude, fullLatLngs.get(0).longitude, saveLongDataEntity.iconLinkOver);
                    setMarker2(fullLatLngs.get(fullLatLngs.size() - 1).latitude, fullLatLngs.get(fullLatLngs.size() - 1).longitude);
                }
                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(fullLatLngs)
                        .width(20)
                        .setDottedLine(false) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));

                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(xuLatLngs)
                        .width(20)
                        .setDottedLine(true) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
            }
        }

        List<LatLng> doneLatLngs = new ArrayList<>();
        if (data.doneSectionId != null && data.doneSectionId.size() > 0) {
            for (int i = 0; i < data.doneSectionId.size(); i++) {
                if (data.doneSectionId.get(i).equals(saveLongDataEntity.sectionId)) {
                    for (int j = 0; j < rideRoteJsonEntity.size(); j++) {
                        doneLatLngs.add(new LatLng(rideRoteJsonEntity.get(j).latitude, rideRoteJsonEntity.get(j).longitude));
                    }
                }
            }
            if (doneLatLngs != null && doneLatLngs.size() > 0) {
                setMarker1(doneLatLngs.get(0).latitude, doneLatLngs.get(0).longitude, saveLongDataEntity.iconLinkOver);
                setMarker1(doneLatLngs.get(doneLatLngs.size() - 1).latitude, doneLatLngs.get(doneLatLngs.size() - 1).longitude, saveLongDataEntity.iconLinkOver);
                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(doneLatLngs)
                        .width(20)
                        .setDottedLine(false) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
            }
        }
        for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
            latLngList.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
            latLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
        }

        polyLineEntity.latLngs.addAll(latLngs);
        polyLineEntityList.add(polyLineEntity);

        setMarker1(latLngs.get(0).latitude, latLngs.get(0).longitude, saveLongDataEntity.iconLink);
        setMarker1(latLngs.get(latLngs.size() - 1).latitude,
                latLngs.get(latLngs.size() - 1).longitude, saveLongDataEntity.iconLink);

        saveLongDataEntity.color = saveLongDataEntity.color.replace("#", "#4d");

        saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                addAll(latLngs)
                .width(20)
                .setDottedLine(true) //打开虚线
                .color(Color.parseColor(saveLongDataEntity.color)));

        for (int j = 0; j < latLngList.size(); j++) {
            newBounds.include(new LatLng(latLngList.get(j).latitude, latLngList.get(j).longitude));
        }
        if (aMap != null) {
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(newBounds.build(), 100), null);
        }
        dismissDialog();
    }

    private void setMarker1(double lat, double lon, String img) {
        View view = View.inflate(this, R.layout.view_custom_mark_small, null);
        ImageView iv_small = view.findViewById(R.id.iv_small);
        Glide.with(App.getInstance()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_small.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }


    private void setMarker(double lat, double lon, String img) {
        View view = View.inflate(this, R.layout.view_custom_mark_flag, null);
        ImageView iv_flag = view.findViewById(R.id.iv_flag);
        Glide.with(App.getInstance()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_flag.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.55f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 头像
     *
     * @param lat
     * @param lon
     * @param
     */
    private void setMarker2(double lat, double lon) {
        View view = View.inflate(this, R.layout.view_custom_mark, null);
        RoundedCornersImage rc_userHeader = view.findViewById(R.id.rc_userHeader);
        TextView tv_company_name = view.findViewById(R.id.tv_company_name);
        Glide.with(getApplicationContext()).load(headImgUrl).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                rc_userHeader.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.55f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }


    private void initAllRoad() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvAllRoad.setLayoutManager(layoutManager);
        allRoadAdapter = new AllRoadAdapter(this, new AllRoadAdapter.OnClick() {
            @Override
            public void challenge(String sectionId1) {
                sectionId = sectionId1;
                onCheck();
            }
        });
        rvAllRoad.addOnScrollListener(listener);//设置自定义滑动滚动条
        rvAllRoad.setAdapter(allRoadAdapter);
        allRoadAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                allRoadAdapter.checkPosition(position);
                allRoadAdapter.notifyDataSetChanged();
                sectionId = allRoadAdapter.getData().get(position).sectionId;
                if (saveLongDataEntities != null && saveLongDataEntities.size() > 0) {
                    for (int i = 0; i < saveLongDataEntities.size(); i++) {
                        if (allRoadAdapter.getData().get(position).sectionId.equals(saveLongDataEntities.get(i).sectionId)) {
                            if (saveLongDataEntities.get(i).roteJsonEntities != null && saveLongDataEntities.get(i).roteJsonEntities.size() > 0) {
                                List<LatLng> latLngs = new ArrayList<>();
                                for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                    RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                    latLngs.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                }
                                if (saveLongDataEntities.get(i).polyline != null) {
                                    saveLongDataEntities.get(i).polyline.setDottedLine(false);
                                } else {
                                    saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#4d", "#");
                                    saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                            addAll(latLngs)
                                            .width(20)
                                            .setDottedLine(false) //打开虚线
                                            .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                }

                            }
                        } else {
                            if (saveLongDataEntities.get(i).roteJsonEntities != null && saveLongDataEntities.get(i).roteJsonEntities.size() > 0) {
                                List<LatLng> latLngs = new ArrayList<>();
                                for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                    RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                    latLngs.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                }
                                if (saveLongDataEntities.get(i).polyline != null) {
                                    saveLongDataEntities.get(i).polyline.setDottedLine(true);

                                } else {
                                    saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#", "#4d");
                                    saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                            addAll(latLngs)
                                            .width(20)
                                            .setDottedLine(true) //打开虚线
                                            .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                }
                            }
                        }
                    }
                }
            }
        });

    }

    private String pathId;

    private void initTextAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvChallengeList.setLayoutManager(layoutManager);
        textAdapter = new RoadTextAdapter(this);
        rvChallengeList.setAdapter(textAdapter);
        if (data != null) {
            if (data.pathPathSectionList != null) {
                for (PathPathSectionListEntity entity : data.pathPathSectionList) {
                    if (entity.pathId.equals(data.nowSectionInfoDTO.pathId)) {
                        entity.isChallenge = true;
                    }
                }
                textAdapter.setNewData(data.pathPathSectionList);
                textAdapter.checkPosition(challengePathIndex);
            }
        }

        textAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                textAdapter.checkPosition(position);
                textAdapter.notifyDataSetChanged();
                pathId = textAdapter.getData().get(position).pathId;
                initLoadRoadLine(textAdapter.getData().get(position));
                rvAllRoad.smoothScrollToPosition(0);
            }
        });
        aMap.setOnPolylineClickListener(new AMap.OnPolylineClickListener() {
            @Override
            public void onPolylineClick(Polyline polyline) {
                List<LatLng> latLngs = polyline.getPoints();
                if (saveLongDataEntities != null && saveLongDataEntities.size() > 0) {
                    for (int i = 0; i < saveLongDataEntities.size(); i++) {
                        SaveLongDataEntity saveLongDataEntity = saveLongDataEntities.get(i);
                        if (saveLongDataEntities.get(i).roteJsonEntities != null && saveLongDataEntities.get(i).roteJsonEntities.size() > 0) {
                            if (latLngs != null && latLngs.size() > 0) {
                                if (latLngs.get(0).latitude != saveLongDataEntity.roteJsonEntities.get(0).latitude &&
                                        latLngs.get(0).longitude != saveLongDataEntity.roteJsonEntities.get(0).longitude) {
                                    List<LatLng> latLngs2 = new ArrayList<>();
                                    for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                        RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                        latLngs2.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                    }
                                    if (saveLongDataEntities.get(i).polyline != null) {
                                        saveLongDataEntities.get(i).polyline.setDottedLine(true);
                                    } else {
                                        saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#", "#4d");
                                        saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                                addAll(latLngs2)
                                                .width(20)
                                                .setDottedLine(true) //打开虚线
                                                .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                    }
                                } else {
                                    List<LatLng> latLngs2 = new ArrayList<>();
                                    for (int j = 0; j < saveLongDataEntities.get(i).roteJsonEntities.size(); j++) {
                                        RideRoteJsonEntity roteLatlngEntity = saveLongDataEntities.get(i).roteJsonEntities.get(j);
                                        latLngs2.add(new LatLng(roteLatlngEntity.latitude, roteLatlngEntity.longitude));
                                    }
                                    if (saveLongDataEntities.get(i).polyline != null) {
                                        saveLongDataEntities.get(i).polyline.setDottedLine(false);
                                    } else {
                                        saveLongDataEntities.get(i).color = saveLongDataEntities.get(i).color.replace("#4d", "#");
                                        saveLongDataEntities.get(i).polyline = aMap.addPolyline(new PolylineOptions().
                                                addAll(latLngs2)
                                                .width(20)
                                                .setDottedLine(false) //打开虚线
                                                .color(Color.parseColor(saveLongDataEntities.get(i).color)));
                                    }

                                    if (data != null && data.pathPathSectionList != null && data.pathPathSectionList.size() > 0) {
                                        for (int j = 0; j < data.pathPathSectionList.size(); j++) {
                                            PathPathSectionListEntity pathSectionListEntity = data.pathPathSectionList.get(j);
                                            for (int k = 0; k < pathSectionListEntity.pathSectionList.size(); k++) {
                                                PathSectionListEntity sectionListEntity = pathSectionListEntity.pathSectionList.get(k);
                                                if (saveLongDataEntities.get(i).sectionId.equals(sectionListEntity.sectionId)) {
                                                    textAdapter.checkPosition(j);
                                                    textAdapter.notifyDataSetChanged();
                                                    sectionId = sectionListEntity.sectionId;
                                                    initLoadRoadLine2(pathSectionListEntity, sectionListEntity.sectionId);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

//    private void showPopup(PathSectionListEntity pathSectionListEntity) {
//        RoadIntroductionPoppupWindow2 poppupWindow2 = RoadIntroductionPoppupWindow2.getInstance(this, pathSectionListEntity);
//        poppupWindow2.show();
//    }

    /**
     * 加载所有路段
     */
    private void loadData() {
        if (null != data) {
            if (null != data.pathPathSectionList && data.pathPathSectionList.size() > 0) {
                pathId = data.pathPathSectionList.get(challengePathIndex).pathId;

                PathPathSectionListEntity pathSectionListEntity = data.pathPathSectionList.get(challengePathIndex);
                initLoadRoadLine(pathSectionListEntity);
            }
        }
    }


    //选出正在挑战的路线
    private void selectChallenge() {
        for (int i = 0; i < data.pathPathSectionList.size(); i++) {
            PathPathSectionListEntity pathPath = data.pathPathSectionList.get(i);
            challengePathIndex = i;
            if (data.nowSectionInfoDTO.pathId.equals(pathPath.pathId)) {
                for (int j = 0; j < pathPath.pathSectionList.size(); j++) {
                    if (data.nowSectionInfoDTO.sectionId.equals(pathPath.pathSectionList.get(j).sectionId)) {
                        data.pathPathSectionList.get(i).pathSectionList.get(j).challenge = ChallengeType.CHALLENGE;//选中正在挑战路线
                        setChallengeFirst(challengePathIndex, j);
                        return;
                    }
                }
            }
        }
    }

    /**
     * 将挑战中的路段排在第一位
     */
    private void setChallengeFirst(int pathIndex, int sectionIndex) {
        PathSectionListEntity pathSectionListEntity = data.pathPathSectionList.get(pathIndex).pathSectionList.get(sectionIndex);
        data.pathPathSectionList.get(pathIndex).pathSectionList.remove(sectionIndex);
        data.pathPathSectionList.get(pathIndex).pathSectionList.add(0, pathSectionListEntity);
    }

    private void setChallengeStatus() {
        for (int i = 0; i < data.pathPathSectionList.size(); i++) {
            PathPathSectionListEntity pathPath = data.pathPathSectionList.get(i);
            for (int j = 0; j < pathPath.pathSectionList.size(); j++) {
                if (!data.nowSectionInfoDTO.sectionId.equals(pathPath.pathSectionList.get(j).sectionId)) {
                    if (data.doneSectionId.contains(pathPath.pathSectionList.get(j).sectionId)) {
                        data.pathPathSectionList.get(i).pathSectionList.get(j).challenge = ChallengeType.FINISH;
                    } else
                        data.pathPathSectionList.get(i).pathSectionList.get(j).challenge = ChallengeType.UNFINISH;
                }
            }
        }
    }

    @OnClick({R.id.top_btn_left, R.id.ll_road_introduce})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.ll_road_introduce:
                if (!TextUtils.isEmpty(name) || !TextUtils.isEmpty(introduction)) {
                    CommonDetailsPoppupWindow.getInstance(this, name, introduction, 0).show();
                }
                break;
            case R.id.tv_sure_check:
                onCheck();
                break;
        }
    }

    private boolean isCoed;

    private void onCheck() {
        JSONObject object = new JSONObject();
        try {
            object.put("delOldSection", isCoed);
            object.put("sectionId", sectionId);
            object.put("pathId", pathId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showDialog();
        new ChallengeAPI().onCheckRoadSection(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 1) {
                    showPopup(response.getMessage());
                } else {
                    isCoed = false;
                    ToastUtils.showShort(response.getMessage());
                    EventBus.getDefault().post(new EventBusEntity(100));
                    finish();
                }
            }
        });
    }

    private void showPopup(String message) {
        CommonDetailsPoppupWindow detailsPoppupWindow = CommonDetailsPoppupWindow.getInstance(this, "", message, 1);
        detailsPoppupWindow.show();
        detailsPoppupWindow.setOnClickListenr(new CommonDetailsPoppupWindow.OnClickListenr() {
            @Override
            public void onCancelClick() {
                isCoed = false;
            }

            @Override
            public void onSureClick() {
                isCoed = true;
                onCheck();
            }
        });
    }

    RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //整体的总宽度，注意是整体，包括在显示区域之外的。
            int temp = recyclerView.computeHorizontalScrollRange();
            //计算水平滚动的距离
            int offset = recyclerView.computeHorizontalScrollOffset();
            //计算水平滚动的范围
            int extent = recyclerView.computeHorizontalScrollExtent();
            //计算滑动比例
            float proportion = (float) (offset * 1.0 / (temp - extent));
            //计算滚动条宽度
            float transMaxRange = rlLine.getWidth() - mainLine.getWidth();
            //设置滚动条移动
            mainLine.setTranslationX(transMaxRange * proportion);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }
}
